const {
  CommonBizLogicError,
  NetworkError,
  JxbResponse,
  HttpResponse
} = require("../../../utils/network");
const {
  default: InteractionUtil
} = require("../../../shell/ui/interaction");
const {
  default: SessionUtil
} = require("../../../data/session/session");

// subPage/goodsAi/recogResult/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shotPhotoSrc: '', // 拍摄的图片
    matched: [],
    recogStatus: -1, // 识别状态 -1 正在识别，1=成功，2=识别失败
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let {
      pSrc
    } = options;
    if (typeof pSrc !== 'string' && pSrc.length === 0) {
      InteractionUtil.showAlert("无效的图片信息，识别失败！").then(optRes => {
        wx.navigateBack({
          fail: (err) => {
            console.log('返回失败', err)
            wx.switchTab({
              url: 'pages/index/index',
            })
          }
        })
      })
      return;
    }
    InteractionUtil.showLoading('识别中...')
    pSrc = decodeURI(pSrc)
    this.doRecognize(pSrc).then(jxbRes => {
      InteractionUtil.hideLoading()
      const {
        _data
      } = jxbRes
      const {
        data
      } = _data
      const {
        predicted_goods,
        matched
      } = data
      // 识别成功
      this.setData({
        shotPhotoSrc: pSrc,
        recogStatus: 1,
        goodsInfo: predicted_goods,
        matched
      })
    }).catch(err => {
      InteractionUtil.hideLoading()
      this.setData({
        shotPhotoSrc: pSrc,
        recogStatus: 2,
        errorMessage: err.message
      })
    })
  },

  /**
   * 执行识别
   * 
   * @param {string} imgSrc 图片地址或图片数据流
   * @returns Promise<JxbResponse>
   */
  doRecognize(imgSrc) {
    return SessionUtil.getInstance().then(session => {
      return new Promise((resolve, reject) => {
        wx.uploadFile({
          filePath: imgSrc,
          name: 'wine_photo',
          url: 'https://www.dobado.cn/goodsAi/recognizeWine/index',
          header: {
            token: session.token,
          },
          success: (res) => {
            // uploadFile 接口返回的是字符串，需要转为json
            if (typeof res.data === "string") {
              res.data = JSON.parse(res.data)
            }
            let jxbResp = new JxbResponse(res.data)
            if (!jxbResp.isOk()) {
              let err = new CommonBizLogicError(jxbResp.message, jxbResp.errorCode, jxbResp, new HttpResponse(res))
              console.log("图片识别失败", err)
              reject(err);
            } else {
              resolve(jxbResp)
            }
          },
          fail: err => {
            console.log("上传时网络出错！", err)
            InteractionUtil.showNotice("网络出错！" + err.message)
            reject(new NetworkError(err.errMsg, err));
          }
        })
      })
    })
  },
  // 重拍、返回拍照界面
  rehotograph() {
    wx.navigateTo({
      url: '/subPage/goodsAi/recognize/index',
    })
  }
})